const { Admin } = require("../models/adminModel");
let jwt = require("jsonwebtoken")

async function register(req, res, next) {
    const { username, password } = req.body
    // console.info(username)
    const userAlreadyExists = await Admin.find({ username })
    if (userAlreadyExists.length > 0) {
        res.send({
            msg: "User already exists, try use other username",
            status: 0
        })
    } else {
        await Admin.create({ username, password })
        res.send({
            msg: "register success",
            status: 1
        })
    }

}

async function login(req, res, next) {
    const { username, password } = req.body
    const data = await Admin.find({ username, password })
    if (data.length > 0) {
        let token = jwt.sign(
            { username },
            "iouhfioahufh",
            { expiresIn: 60 * 100 },
        )
        res.send({
            data,
            token,
            met: "login success",
            status: 1,
        })
    } else {
        res.send({
            msg: "login failed",
            status: 0
        })
    }
}

async function getAllAdmins(req, res, next) {
    const data = await Admin.find()
    if (data.length > 0) {
        res.send({
            msg: "got all admins",
            data,
            status: 1,
        })
    } else {
        res.send({
            msg: "no admin data found",
            status: 0,
        })
    }
}

async function changeAdminAccess(req, res, next) {
    const {_id} = req.body
    const gotAdmin = await Admin.find({ _id })
    let newStatus = !gotAdmin[0].status-current
    const result = await Admin.updateOne({ _id }, { status: newStatus })
    res.send({
        msg: "change admin status success",
        data: result,
        status: 0,
    })
}

async function deleteAdminByID(req,res,next){
    const {_id} = req.body
    await Admin.deleteOne({_id})
    res.send({
        msg:"Admin removal success",
        status:1
    })
    
}

module.exports = { register, login, getAllAdmins, changeAdminAccess,deleteAdminByID }